package org.jeecg.modules.mes.produce.service.impl;

import com.alibaba.csp.sentinel.util.StringUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.mes.chiefdata.entity.MesChiefdataBomitem;
import org.jeecg.modules.mes.client.SystemClient;
import org.jeecg.modules.mes.client.TransactionClient;
import org.jeecg.modules.mes.order.entity.MesOrderProduce;
import org.jeecg.modules.mes.produce.entity.MesOnlineMaterieltable;
import org.jeecg.modules.mes.produce.entity.MesOnlineMaterieltableMain;
import org.jeecg.modules.mes.produce.mapper.MesOnlineMaterieltableMainMapper;
import org.jeecg.modules.mes.produce.mapper.MesOnlineMaterieltableMapper;
import org.jeecg.modules.mes.produce.service.IMesOnlineMaterieltableMainService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * @Description: 制造中心-在线料表-主表
 * @Author: jeecg-boot
 * @Date: 2021-05-13
 * @Version: V1.0
 */
@Service
public class MesOnlineMaterieltableMainServiceImpl extends ServiceImpl<MesOnlineMaterieltableMainMapper, MesOnlineMaterieltableMain> implements IMesOnlineMaterieltableMainService {

    @Autowired
    private MesOnlineMaterieltableMainMapper mesOnlineMaterieltableMainMapper;
    @Autowired
    private MesOnlineMaterieltableMapper mesOnlineMaterieltableMapper;
    @Autowired
    private TransactionClient transactionClient;
    @Autowired
    private SystemClient systemClient;

    @Override
    @Transactional
    public void delMain(String id) {
        mesOnlineMaterieltableMapper.deleteByMainId(id);
        mesOnlineMaterieltableMainMapper.deleteById(id);
    }

    @Override
    @Transactional
    public void delBatchMain(Collection<? extends Serializable> idList) {
        for (Serializable id : idList) {
            mesOnlineMaterieltableMapper.deleteByMainId(id.toString());
            mesOnlineMaterieltableMainMapper.deleteById(id);
        }
    }

    public boolean updateMain(String productCode, String lineType) {
        System.out.println("updateMain:" + productCode + "  " + lineType);
        QueryWrapper<MesOnlineMaterieltableMain> queryWrapper = new QueryWrapper();
        queryWrapper.eq("product_code", productCode);
        queryWrapper.eq("line_type", lineType);
        List<MesOnlineMaterieltableMain> list1 = mesOnlineMaterieltableMainMapper.selectList(queryWrapper);
//        System.out.println("updateMain size:"+list1.size());
        if (list1.size() > 0) {
            MesOnlineMaterieltableMain main = list1.get(0);
            main.setCreateTime(DateUtils.getDate());
            mesOnlineMaterieltableMainMapper.updateById(main);
            System.out.println("updateMain true ");
            return true;
        }
        System.out.println("updateMain false ");
        return false;
    }

    @Transactional
    public boolean importMesOnlineMaterieltable(HttpServletRequest request, HttpServletResponse response, String mainId) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        if (StringUtil.isEmpty(mainId)) {
            throw new RuntimeException("请选中一条主表数据导入！");
        }
        MesOnlineMaterieltableMain maininfo = mesOnlineMaterieltableMainMapper.selectById(mainId);
        if (maininfo == null) {
            throw new RuntimeException("未找到该在线料表主表信息！");
        }
        if (StringUtils.isBlank(maininfo.getProductCode())) {
            throw new RuntimeException("在线料表主表信息有误！未填写成品料号！");
        }
        if (StringUtils.isBlank(maininfo.getLineType())) {
            throw new RuntimeException("在线料表主表信息有误！未填写线别！");
        }

        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<MesOnlineMaterieltable> list = ExcelImportUtil.importExcel(file.getInputStream(), MesOnlineMaterieltable.class, params);
                int i = 0;
                for (MesOnlineMaterieltable temp : list) {
                    i++;
                    temp.setMainId(mainId);
                    temp.setProductCode(maininfo.getProductCode());
                    temp.setProductName(maininfo.getProductName());
                    temp.setLineType(maininfo.getLineType());
                    if (StringUtils.isBlank(temp.getQuery5())) {
                        temp.setQuery5("正面");
                    }
                    if (StringUtils.isBlank(temp.getMaterielCode())) {
                        throw new RuntimeException("第" + i + "行" + "物料料号不能为空！");
                    }
                    if (StringUtils.isBlank(temp.getPointNum())) {
                        throw new RuntimeException("第" + i + "行" + "点数不能为空！");
                    }
                    if (StringUtils.isBlank(temp.getLineType())) {
                        throw new RuntimeException("第" + i + "行" + "线别不能为空！");
                    }
                    mesOnlineMaterieltableMapper.insert(temp);
                }
//                long start = System.currentTimeMillis();
                //mesOnlineMaterieltableService.saveBatch(list);
                //远程调用bom，更新正反面用量
                for (MesOnlineMaterieltable temp : list) {
                    //根据成品料号去生产订单查询，是否有该生产订单；
                    if (StringUtils.isNotBlank(temp.getPointNum()) && !"0".equals(temp.getPointNum().trim())) {
                        boolean mark = systemClient.getMCodebomitemForInS(temp.getProductCode(), temp.getMaterielCode(), temp.getQuery5(), temp.getPointNum());
                        if (!mark) {
                            throw new RuntimeException("未在bom中找到成品料号为：" + temp.getProductCode() + "和物料料号为：" + temp.getMaterielCode() + "的bom信息，无法同步正反面用量！");
                        }
                    }
                }
                //log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
                //return Result.ok("文件导入成功！数据行数：" + list.size());
                return true;
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                throw new RuntimeException("文件导入失败:" + e.getMessage());
                //return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return false;
        //return Result.error("文件导入失败！");
    }

    /**
     * 在线料表-主表-添加
     */
    @Override
    public Result<?> add(MesOnlineMaterieltableMain mesOnlineMaterieltableMain) {
        //根据成品料号去生产订单查询，是否有该生产订单；
        List<MesOrderProduce> orderProduceList = transactionClient.getOrderProduceList(mesOnlineMaterieltableMain.getProductCode(), mesOnlineMaterieltableMain.getLineType());
        if (orderProduceList.size() == 0) {
            //throw new RuntimeException("未找到该成品料号和生产线别的生产订单！");
            return Result.error("未找到该成品料号和生产线别的生产订单！");
        }

        QueryWrapper<MesOnlineMaterieltableMain> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("product_code", mesOnlineMaterieltableMain.getProductCode());
        queryWrapper.eq("line_type", mesOnlineMaterieltableMain.getLineType());
        List<MesOnlineMaterieltableMain> list = mesOnlineMaterieltableMainMapper.selectList(queryWrapper);
        if (com.epms.util.ObjectHelper.isNotEmpty(list)) {
            //throw new RuntimeException("存在相同的数据，请查验后添加！");
            return Result.error("存在相同的数据，请查验后添加！");
        }

        if (mesOnlineMaterieltableMainMapper.insert(mesOnlineMaterieltableMain) != 1) {
            return Result.error("添加失败！");
        }

        List<MesOnlineMaterieltableMain> mesOnlineMaterielTableMains = mesOnlineMaterieltableMainMapper.selectList(queryWrapper);
        if (com.epms.util.ObjectHelper.isNotEmpty(mesOnlineMaterielTableMains)) {
            this.addMesOnlineMaterielTable(mesOnlineMaterieltableMain, mesOnlineMaterielTableMains.get(0));
        }

        return Result.ok("添加成功！");
    }

    /**
     * 添加子表
     */
    private void addMesOnlineMaterielTable(MesOnlineMaterieltableMain mesOnlineMaterieltableMain, MesOnlineMaterieltableMain mesOnlineMaterielTableMains) {
        //查询BOM
        List<MesChiefdataBomitem> mesChiefDataBomItems = systemClient.queryByMcodeZu(mesOnlineMaterieltableMain.getProductCode());
        if (com.epms.util.ObjectHelper.isNotEmpty(mesChiefDataBomItems)) {
            for (MesChiefdataBomitem item : mesChiefDataBomItems) {
                this.addMesOnlineMaterielTable(mesOnlineMaterieltableMain, mesOnlineMaterielTableMains, item, "正面");
                if (StringUtils.isNotBlank(item.getInverseQuantity()) && new BigDecimal(item.getInverseQuantity()).compareTo(BigDecimal.ZERO) == 1) {
                    this.addMesOnlineMaterielTable(mesOnlineMaterieltableMain, mesOnlineMaterielTableMains, item, "反面");
                }
            }
        }
    }

    private void addMesOnlineMaterielTable(MesOnlineMaterieltableMain mesOnlineMaterieltableMain, MesOnlineMaterieltableMain mesOnlineMaterielTableMains, MesChiefdataBomitem item, String query5) {
        MesOnlineMaterieltable mesOnlineMaterieltable = new MesOnlineMaterieltable();
        mesOnlineMaterieltable.setMainId(mesOnlineMaterielTableMains.getId());
        mesOnlineMaterieltable.setCreateBy(mesOnlineMaterieltableMain.getCreateBy());//创建人
        mesOnlineMaterieltable.setCreateTime(mesOnlineMaterieltableMain.getCreateTime());//创建日期
        mesOnlineMaterieltable.setSysOrgCode(mesOnlineMaterieltableMain.getSysOrgCode());//所属部门
        mesOnlineMaterieltable.setLineType(mesOnlineMaterieltableMain.getLineType());//线别
        mesOnlineMaterieltable.setProductCode(mesOnlineMaterieltableMain.getProductCode());//成品料号
        mesOnlineMaterieltable.setProductName(mesOnlineMaterieltableMain.getProductName());//成品名称
        mesOnlineMaterieltable.setMaterielCode(item.getMaterielCode());//物料料号
        mesOnlineMaterieltable.setMaterielName(item.getMaterielName());//物料名称
        mesOnlineMaterieltable.setMaterielGague(item.getMaterielGauge());//物料规格
        mesOnlineMaterieltable.setPointLocation(item.getSpot());//点位
        mesOnlineMaterieltable.setQuery5(query5);//正面/反面
        mesOnlineMaterieltable.setPointNum(item.getQuantity());//正面用量
        if("反面".equals(query5)){
            mesOnlineMaterieltable.setPointNum(item.getInverseQuantity());//反面用量
        }
        //mesOnlineMaterieltable.setId(null);
        //mesOnlineMaterieltable.setPassage();//通道
        //mesOnlineMaterieltable.setDeviceSerial();//设备序号
        //mesOnlineMaterieltable.setMaterielStation();//料站
        //mesOnlineMaterieltable.setTrayPlate();//TRAY盘物料
        //mesOnlineMaterieltable.setSkipToken();//跳过标志
        //mesOnlineMaterieltable.setTrack();//轨道
        //mesOnlineMaterieltable.setSelfBarcode();//自制条码
        //mesOnlineMaterieltable.setShelfCode();//货架编码
        mesOnlineMaterieltableMapper.insert(mesOnlineMaterieltable);
    }
}
